package com.taoyige.ui;

import java.text.DecimalFormat;
import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.taoyige.AppConfig;
import com.taoyige.AppContext;
import com.taoyige.AppException;
import com.taoyige.R;
import com.taoyige.api.ApiClient;
import com.taoyige.bean.Address;
import com.taoyige.bean.Goods;
import com.taoyige.bean.Order;
import com.taoyige.bean.URLs;
import com.taoyige.common.APPUpdateUtil;
import com.taoyige.common.UIHelper;
import com.taoyige.widget.BadgeView;
import com.taoyige.widget.LoadingDialog;

/**
 * 首页
 * @author peter
 * @version 1.0
 *  @date 2014-11-18
 */
public class MainActivity extends BaseActivity {

	private AppContext appContext;
	private Context publiccontext;
	private Order publicOrder;
	
	private DoubleClickExitHelper doubleClickExitHelper;
	
	private TextView title;
	private ImageView image;
	private TextView soldCount;
	private TextView  storeCount;
	private TextView  originPrice;
	private TextView   promotionPrice;
	private TextView   discount;
	private LinearLayout main_goods;
	private LinearLayout main_buy;

	private long mHour;  
	private long mMin;  
	private long mSecond;
	private Boolean timeIsRun = true;  

	private ImageButton mainUser;
	private RelativeLayout commingsoon;
	
	private ImageView commingsoonimage;
	private Goods goods;
	private Handler handler;
	private Handler handlerA;
	private Button ivbuy;
	
	private LoadingDialog loading;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		doubleClickExitHelper = new DoubleClickExitHelper(this);
		
		appContext = (AppContext) getApplication();
		// 网络连接判断
		
		if (!appContext.isNetworkConnected())
			UIHelper.ToastMessage(this, R.string.network_not_connected);
		
		//初始化登陆
		try {
			appContext.initLoginInfo();
		} catch (AppException e) {
			e.printStackTrace();
		}
				
		this.initView();
		this.initDataA();
		// 检查新版本
		
//		if (appContext.isCheckUp()) {
//			APPUpdateUtil.getUpdateManager().checkAppUpdate(this, true);
//		}
		
		// 检查是否需要下载欢迎图片
		this.checkWelcomeImage();
				
		
		
	}
	
	private void initView(){
		title = (TextView)findViewById(R.id.goods_index_item_title);
		image= (ImageView)findViewById(R.id.goods_index_item_image_url);
		soldCount= (TextView)findViewById(R.id.goods_index_item_sold_count);
		storeCount= (TextView)findViewById(R.id.goods_index_item_store_count);
		originPrice= (TextView)findViewById(R.id.goods_index_item_origin_price);
		promotionPrice= (TextView)findViewById(R.id.goods_index_item_promotion_price);
		discount= (TextView)findViewById(R.id.goods_index_item_discount);
		ivbuy=(Button)findViewById(R.id.iv_buy);
		
		commingsoon=(RelativeLayout)findViewById(R.id.main_commingsoon_footer);
		commingsoonimage= (ImageView)findViewById(R.id.iv_comming_soon_image);
		
		commingsoon.setVisibility(View.GONE);
		main_goods=(LinearLayout) findViewById(R.id.main_goods);
		main_buy=(LinearLayout) findViewById(R.id.main_buy);
		
		mainUser=(ImageButton) findViewById(R.id.main_user);
		
		BadgeView.showBadge(MainActivity.this, mainUser);
	}
	
	private void initDataA() {
		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (loading != null)
					loading.dismiss();
				if (msg.what == 1 && msg.obj != null) {
					
					goods = (Goods) msg.obj;
					//加载商品图片
					UIHelper.showGoodsImage(image, goods.getBannerUrl());
					
					title.setText(goods.getTitle());
					soldCount.setText("已售："+goods.getSalesVolume()+"件");
					storeCount.setText("库存："+goods.getCount()+"件");
					originPrice.setText("原价：￥"+goods.getOriPrice());
					promotionPrice.setText("￥"+goods.getPrice());
					Double disc=(goods.getPrice()/goods.getOriPrice())*10;
					if(disc>1){
						DecimalFormat df = new DecimalFormat("#.0");
				        discount.setText(df.format(disc)+"折");
					}else{
						  discount.setText("0.1折");
					}

					image.setOnClickListener(imageClickListener);
					title.setOnClickListener(imageClickListener);
					
					if(goods.getServerTime().after(goods.getSaleStartTime())){
						Order order=new Order();
						order.setProduct(goods);
						order.setTotalPrice(goods.getPrice()+goods.getFreight());
						ivbuy.setText("立刻闪购");
						ivbuy.setTag(order);
						ivbuy.setOnClickListener(ivbuyClickListener);
					}else{
						Date begin = goods.getServerTime();
						Date end = goods.getSaleStartTime();
						long l=end.getTime()-begin.getTime();   
						mHour=(l/(60*60*1000));   
						mMin=((l/(60*1000))-mHour*60);   
						mSecond=(l/1000-mHour*60*60-mMin*60);  
						timeRun();
					}
					mainUser.setOnClickListener(userClickListener);
				}else if (msg.what == 2 && msg.obj != null) {
					Goods goodsCommingsoon = (Goods)msg.obj;
					if(goodsCommingsoon.getResult().getErrorCode()==200){
						UIHelper.showGoodsImage(commingsoonimage, URLs.HTTP+URLs.HOST+goodsCommingsoon.getBannerUrl());
						commingsoonimage.setColorFilter(R.color.blue);
						commingsoon.setVisibility(View.VISIBLE);
						commingsoon.setOnClickListener(commingClickListener);
						commingsoon.setTag(goodsCommingsoon.getId());
					}
				}else if(msg.what==3){
					mSecond--;  
					if(mSecond < 0) {
						mMin--;  
						mSecond = 59;  
						if (mMin < 0) {  
							mMin = 59;  
							mHour--;  
							if (mHour < 0) {  
							}
						}
					}
					ivbuy.setText(mHour+":"+mMin+":"+mSecond);
					if (mHour==0&&mMin==0&&mSecond==0) {  
						timeIsRun=false;
						Order order=new Order();
						order.setProduct(goods);
						order.setTotalPrice(goods.getPrice()+goods.getFreight());
						ivbuy.setText("立刻闪购");
						ivbuy.setTag(order);
						ivbuy.setOnClickListener(ivbuyClickListener);
					}  
				}else if (msg.obj != null) {
					((AppException) msg.obj).makeToast(MainActivity.this);
				}
				
				main_goods.setVisibility(View.VISIBLE);
				main_buy.setVisibility(View.VISIBLE);
			}
		};
		this.loadGoodsIndexThread();
	}
	
	private void loadGoodsIndexThread() {
		main_goods.setVisibility(View.INVISIBLE);
		main_buy.setVisibility(View.INVISIBLE);
		
		loading = new LoadingDialog(this);
		loading.show();
		
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					Goods  goods= ((AppContext) getApplication()).getGoodsIndex();
					msg.what = 1;
					msg.obj = goods;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					Goods  goods= ((AppContext) getApplication()).getGoodsCommingSoon();
					msg.what = 2;
					msg.obj = goods;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();

	}
	
	private void timeRun(){
		new Thread(){  
			public void run() {  
				while (timeIsRun) {  
					Message msg = new Message();
					try {
						Thread.sleep(1000);
						msg.what = 3; 
					} catch (InterruptedException e) {
						e.printStackTrace();
						msg.what = -1;
						msg.obj = e;
					}  
					handler.sendMessage(msg);
				}
			}
		}.start();  
	}
	
	private View.OnClickListener imageClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			String  id=goods!=null?goods.getId():"0";
			UIHelper.showGoodsDetail(v.getContext(), id);
		}
	};
	private View.OnClickListener commingClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			UIHelper.showGoodsCommingsoonDetail(v.getContext(), (String)v.getTag());
		}
	};
	private View.OnClickListener userClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			//判断用户是否已经登陆
			//UIHelper.showUserCenter(v.getContext(),AppConfig.BADGE_NO);
			
			if(appContext.isLogin()){
				UIHelper.showUserCenter(v.getContext(),AppConfig.BADGE_NO);
			}else{
				UIHelper.showUserLogin(v.getContext(),AppConfig.LOGIN_TYPE_USER_AVATAR_BUTTON);
			}
		
		}
	};
	private View.OnClickListener ivbuyClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			publiccontext = v.getContext();
			if(appContext.isLogin()){
				publicOrder = (Order)v.getTag();
				handlerA = new Handler(){
					public void handleMessage(Message msg) {
						if (loading != null)
							loading.dismiss();
						if (msg.what == 1 && msg.obj != null) {
							Address address = (Address) msg.obj;
							if(address.getResult().getErrorCode()==200){
								UIHelper.showBuyNow(publiccontext,publicOrder);
							}else{
								Intent intent = new Intent(publiccontext, AddressDetailActivity.class);
								intent.putExtra("order", publicOrder);
								intent.putExtra("status", 1);
								publiccontext.startActivity(intent);
							}
						}else if (msg.obj != null) {
							((AppException) msg.obj).makeToast(MainActivity.this);
						}
					}
				};
				new Thread() {
					public void run() {
						Message msg = new Message();
						try {
							Address  addr= appContext.getAddrDefault(appContext.getLoginUid());
							msg.what = 1;
							msg.obj = addr;
						} catch (AppException e) {
							e.printStackTrace();
							msg.what = -1;
							msg.obj = e;
						}
						handlerA.sendMessage(msg);
					}
				}.start();
			}else{
				UIHelper.showUserLogin(v.getContext(),AppConfig.LOGIN_TYPE_USER_AVATAR_BUTTON);
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean flag = true;
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 是否退出应用
			return doubleClickExitHelper.onKeyDown(keyCode, event);
		} else {
			flag = super.onKeyDown(keyCode, event);
		}
		return flag;
	}
	
	private void checkWelcomeImage() {
		if (!appContext.isNetworkConnected()) {
			return;
		}
		new Thread(){
			public void run() {
				try {
					ApiClient.checkBackGround(appContext);
				} catch (AppException e) {
				}
			}
		}.start();
	}
	
}
